/**
 * 
 */
package mx.netbrain.bean;

import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;

import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;

/**
 * @author julian
 * 
 */
public class LanguageBean implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8300583738454396109L;

	private String localeCode;

	private static Map<String, Object> countries;

	private Locale locale = FacesContext.getCurrentInstance().getViewRoot()
			.getLocale();

	static {
		countries = new LinkedHashMap<String, Object>();
		countries.put("English", Locale.ENGLISH); // label, value
		countries.put("Español", Locale.getDefault());
	}

	public Map<String, Object> getCountriesInMap() {
		return countries;
	}

	public String getLocaleCode() {
		if (localeCode == null) {
			localeCode = "en";
		}
		return localeCode;
	}

	public void setLocaleCode(String localeCode) {
		this.localeCode = localeCode;
	}

	public Locale getLocale() {
		return locale;
	}

	public void countryLocaleCodeChanged(ValueChangeEvent e) {

		String newLocaleValue = e.getNewValue().toString();

		// loop a map to compare the locale code
		for (Map.Entry<String, Object> entry : countries.entrySet()) {
			System.out.println();
			if (entry.getValue().toString().equals(newLocaleValue)) {
				FacesContext.getCurrentInstance().getViewRoot()
						.setLocale((Locale) entry.getValue());
				UIViewRoot viewRoot = FacesContext.getCurrentInstance()
						.getViewRoot();
				viewRoot.setLocale(new Locale(newLocaleValue));
			}
		}

	}
}
